# -*- coding: utf-8 -*-
import os

from flask import request, current_app
from flask_restx import Resource, Namespace, fields

from utils.response import ResponseMaker
from app.extentions import db
from utils.jwt import JWTUtil


upload_api = Namespace("upload", description="上传", path="/api/upload")


upload_picture_model = upload_api.model('UploadPictureModel', {
    'file': fields.String(required=True, description='账号')
})


@upload_api.route('/picture')
class PictureUploadAPI(Resource):
    @upload_api.doc(description='上传图片')
    @JWTUtil.verify_token_decorator(request)
    def post(self, *args, **kwargs):
        file = request.files['file']

        uid = request.user.id
        save_dir = os.path.join(current_app.config['ROOT_DIR'], "pictures", str(uid))
        os.makedirs(save_dir, exist_ok=True)

        save_fp = os.path.join(save_dir, file.filename)

        try:
            with open(save_fp, "wb") as f:
                f.write(file.read())
        except Exception as e:
            raise e

        resp_data = {
            "picture_path": save_fp
        }

        return ResponseMaker.success(resp_data)